package ali

import (
	"encoding/json"
	"errors"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	dysmsapi20170525 "github.com/alibabacloud-go/dysmsapi-20170525/v4/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	"go.uber.org/zap"
	"sheep_script/global"
	"strings"
)

func CreateClient() (_result *dysmsapi20170525.Client, _err error) {
	// 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考。
	// 建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378661.html。
	config := &openapi.Config{
		// 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
		AccessKeyId: &global.Config.Sms.Ali.AccessKeyId,
		// 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
		AccessKeySecret: &global.Config.Sms.Ali.AccessKeySecret,
		Endpoint:        &global.Config.Sms.Ali.Endpoint,
	}
	_result = &dysmsapi20170525.Client{}
	_result, _err = dysmsapi20170525.NewClient(config)
	return _result, _err
}

func SendVerifyCode(phone, code string) (_err error) {
	client, _err := CreateClient()
	if _err != nil {
		return _err
	}

	templateParamMap := map[string]string{}
	templateParamMap["code"] = code
	templateParamJson, _ := json.Marshal(templateParamMap)
	templateParam := string(templateParamJson)

	sendSmsRequest := &dysmsapi20170525.SendSmsRequest{
		PhoneNumbers:  &phone,
		SignName:      &global.Config.Sms.Ali.SignName,
		TemplateCode:  &global.Config.Sms.Ali.TemplateCode,
		TemplateParam: &templateParam,
	}

	tryErr := func() (_e error) {
		defer func() {
			if r := tea.Recover(recover()); r != nil {
				_e = r
			}
		}()
		// 复制代码运行请自行打印 API 的返回值
		global.Logger.Info("ali-sms-request:", zap.Any("request:", sendSmsRequest))
		result, _err := client.SendSmsWithOptions(sendSmsRequest, &util.RuntimeOptions{})
		global.Logger.Info("ali-sms-result:", zap.Any("result:", result))
		if _err != nil {
			return _err
		}

		return nil
	}()
	if tryErr != nil {
		var err = &tea.SDKError{}
		var _t *tea.SDKError
		if errors.As(tryErr, &_t) {
			err = _t
		}
		// 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
		// 错误 message
		global.Logger.Error("ali-sms-error:", zap.Any("err:", err))
		// 诊断地址
		var data interface{}
		d := json.NewDecoder(strings.NewReader(tea.StringValue(err.Data)))
		d.Decode(&data)
		if m, ok := data.(map[string]interface{}); ok {
			recommend, _ := m["Recommend"]
			global.Logger.Error("ali-sms-recommend-error:", zap.Any("data:", recommend))
		}
		_, _err = util.AssertAsString(err.Message)
		if _err != nil {
			return _err
		}
	}
	return _err
}
